﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;

namespace ES.Client
{
    public static class Cache
    {
        static object _lock = new object();

        public static void Set(string key, object value, int expireSecond)
        {
            if (string.IsNullOrEmpty(key))
            {
                return;
            }

            if (HttpRuntime.Cache.Get(key) == null)
            {
                lock (_lock)
                {
                    if (HttpRuntime.Cache.Get(key) == null)
                    {
                        HttpRuntime.Cache.Add(key, value, null, DateTime.Now.AddSeconds(expireSecond), TimeSpan.Zero, CacheItemPriority.Normal, null);
                    }
                }
            }
        }

        public static void Set(string key, object value)
        {
            if (string.IsNullOrEmpty(key))
            {
                return;
            }

            if (HttpRuntime.Cache.Get(key) == null)
            {
                lock (_lock)
                {
                    if (HttpRuntime.Cache.Get(key) == null)
                    {
                        HttpRuntime.Cache.Add(key, value, null, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.Normal, null);
                    }
                }
            }
        }

        public static object Get(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return null;
            }

            return HttpRuntime.Cache.Get(key);
        }

        public static void Remove(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return;
            }

            if (HttpRuntime.Cache.Get(key) != null)
            {
                lock (_lock)
                {
                    if (HttpRuntime.Cache.Get(key) != null)
                    {
                        HttpRuntime.Cache.Remove(key);
                    }
                }
            }
        }
    }
}
